<template>
  <div class="app-container">

    <div class="ces-main">

      <v-GetToolBar align="right" :MenuCode="MenuCode" :IsfunEdit='IsfunEdit' :Isfunfail='Isfunfail'
        @handeAdd='handeAdd' @handleEdit='handleEdit' @OpenFindForm='OpenFindForm' @handlexportData='handlexportData'
        @IsfunEdit='handleIsfunEdit' @IsfunDelete='handleIsfunfail' @handleclose='handleclose'></v-GetToolBar>

      <div style="display: flex;">
        <div class="tree" style="width: 200px;">
          <el-tree :data="treeData" width="10px" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
        <ces-table style="width: 40vw;flex: 1" size='mini' :isSelection='false' :isIndex='true' :isSearch='true'
          :isHandle='false' :high="170" :Isfunfail="false" :IsfunEdit='IsfunEdit' :tableData='tableData'
          :tableCols='tableCols' :Search='Search' @refresh="refresh" :time='1500' @handleEdit='handleEdit'
          @handleDelete="delData" @handrowclick="handrowclick" btnName1="按钮">
        </ces-table>
        <div v-if="dialogFormVisible"
          style="width: 700px;height: 82vh;padding-left: 10px;box-shadow: 0px 0px 1px #888; ">
          <el-form :model="name" label-width="80px" label-position="left">
            <Mian-Form ref="refFormData" labelWidth='100px' :FormData='saveConfigurationDate' :tableCols='tableCols'
              :StepSN='0' @handleOpen="handleOpen"></Mian-Form>
          </el-form>
          <el-button type="primary" @click="saveTable">保存</el-button>
          <el-button type="primary" @click="close">关闭</el-button>
        </div>
      </div>
    </div>


    <!--搜索弹框-->
    <el-dialog title="搜索" :visible.sync="SearchDialog" custom-class="dialogClass" class="searchDialog" center
      ref="searchDialog" :modal="false" :close-on-click-modal="true">
      <el-form :model="Search" label-width="90px" ref="searchForm">

        <Search-Form ref="form" :frame="true" size='mini' labelWidth='50px' :searchData='Search' :tableCols='tableCols'
          :searchHandle="searchHandle" @handleEnter='refresh()'></Search-Form>
      </el-form>
      <div slot="footer" :style="{ 'margin-buttom': 0 == 0 ? DialogBtnMargin : DialogBtnMargin }">
        <el-button @click="reform()">重置</el-button>
        <el-button type="primary" @click="refresh()">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog v-if="dialogMenuButton" :visible.sync="dialogMenuButton" :title="编辑" width="800px">
      <el-button type="primary" @click="saveMenuButton">保存</el-button>
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="primary" @click="close">关闭</el-button>
      <ces-tables size='mini' :isSelection='false' :isIndex='true' :isSearch='false' :isHandle='true' :high="300"
        :Isfunfail="true" :IsfunEdit='false' StepSN="0" WFStepSN="0" :tableData='MenuButtonData'
        :tableCols='MenuButtonCols' @handleEdit='handleEdit' @handleDelete="delData" @handrowclick="handrowclick"
        btnName1="按钮">
      </ces-tables>
    </el-dialog>


  </div>
</template>

<script>


//引入组件

import cesTable from "../Common//table.vue";
import cesTables from "../Common//tableDouble.vue";
import SearchForm from "../Common//Search.vue";
import MianForm from "../Common//form.vue";
import vGetToolBar from "../Common/GetToolBar";
import { funDownload, GetTableColsData } from "@/api/Common";
import { getDataList, UpdateForm, DeleteForm, CloseForm, MenuUpdate, MenuButtonUpdate, MenuButtonDelet } from '@/api/System';


export default {
  name: "MenuBill",
  data() {
    //表单查询一般分为input，下拉框，和日期，下面是下拉框时的设置下拉信息的情况，我的项目没有用到，但是留着方便看

    return {
      bottonID: null,
      clickData: [],
      // tableDataSave: [],
      see: [],
      AppCode: null,
      MenuCodeSave: '',
      // treeDataSave: [],
      tableHeight: null,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      MenuButtonCols: [],
      saveConfigurationDateTwo: false,
      MenuButtonData: [],
      dialogFormVisible: true,
      saveConfigurationDate: [],
      dialogMenuButton: false,
      formInline: {
        user: '',
        region: ''
      },
      MenuCode: "A050107",
      tableData: [],//表格数据
      tableCols: [],//表格列数据
      searchHandle: [],
      billID: "",
      IsfunEdit: false,
      Isfunfail: false,
      StepSN: -1,
      WFStepSN: '0',
      Search: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 20, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "009", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件
        AppCode: 'A05',
        // MenuCode:"A05",
        // Status: 2,
        // BillState: "BillStateALL"
      },
      SearchAll: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 0, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "009", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件
        AppCode: 'A05',
        // MenuCode:"A05",
        // Status: 2,
        // BillState: "BillStateALL"
      },
      SearchDialog: false,
      DialogBtnMargin: 0,
      dialogVisible: false,
    }
  },

  components: { //引入组件后注册组件
    cesTable,
    cesTables,
    vGetToolBar,
    SearchForm,
    MianForm
  },
  mounted() {
    this.getTableCols()
    this.getDataList()
    // setTimeout(() => {
    //   this.move()
    // }, 2000);

  },
  methods: {
    move() {
      let modal = this.$refs.draggableModal
      let modalHeader = document.querySelector('.modal-header');

      // Get the modal's current position from the top  
      let pos1 = 0;
      let pos2 = 0;
      let pos3 = 0;
      let pos4 = 0;

      // When the user mouses down on the modal header, get the mouse cursor's x and y positions  
      modalHeader.onmousedown = dragMouseDown;

      function dragMouseDown(e) {
        // alert(11)
        e = e || window.event;
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // Call a function whenever the cursor moves  
        document.onmousemove = elementDrag;
      }

      // Move the modal  
      function elementDrag(e) {
        e = e || window.event;
        // Calculate the new cursor position:  
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // Set the modal's new position:  
        modal.style.top = (modal.offsetTop - pos2) + "px";
        modal.style.left = (modal.offsetLeft - pos1) + "px";
        console.log(modal.style)
      }

      // Stop moving when mouse button is released:  
      function closeDragElement() {
        // Stop moving when mouse button is released:  
        document.onmouseup = null;
        document.onmousemove = null;
      }

      // Close the modal when the close button is clicked  
      function closeModal() {
        modal.style.display = "none";
      }
    },

    async handleNodeClick(data) {
      // debugger
      this.clickData = data
      // this.Search.MenuCode = data.MenuCode
      this.Search.jsWhere = `and MenuCode = '${data.MenuCode}' or ParentCode = '${data.MenuCode}'`
      if (!data.MenuCode) this.Search.jsWhere = ''
      const res = await getDataList({ data: JSON.stringify(this.Search) });
      this.tableData = res.data.Table;
      this.Search.total = this.tableData.length

      this.MenuCodeSave = data.MenuCode

      let Configuration = await MenuUpdate({
        MenuCode: data.MenuCode || 'A0501',
        IsPostBack: false,
      })
      this.saveConfigurationDate = Configuration.data.Table[0];

      // debugger
    },

    add() {
      var rowOne = {
        ButtonClass: null,
        ButtonCode: "add",
        ButtonImageUrl: null,
        ButtonOrder: null,
        ID: null,
        IsEnable: null,
        MenuCode: this.bottonID,
        OnClick: null,
      };
      this.MenuButtonData.push(rowOne);
    },

    async saveMenuButton() {
      let result = await MenuButtonUpdate({
        InterID: 213,
        HeadDate: JSON.stringify(this.MenuButtonCols),
        BodyDate: JSON.stringify(this.MenuButtonData),
        billID: this.MenuButtonData[0].MenuCode,
        IsPostBack: true,
      })
      console.log(result)
      if (result.code === 20000) {

        this.dialogMenuButton = false
        this.$notify({
          title: result.msg,
          dangerouslyUseHTMLString: true,
          message: "",
          type: "success",
        });
      }
    },


    async saveTable() {
      // this.saveConfigurationDate
      // debugger
      let result = await MenuUpdate({
        IsPostBack: true,
        MenuCode: this.saveConfigurationDate.MenuCode,
        HeadDate: JSON.stringify(this.saveConfigurationDate),
        InterID: 213
      })
      if (result.code === 20000) {

        this.dialogMenuButton = false
        this.$notify({
          title: result.msg,
          dangerouslyUseHTMLString: true,
          message: "",
          type: "success",
        });
      }
      // this.close()
      const res = await getDataList({ data: JSON.stringify(this.SearchAll) })
      const treeData = this.arrayToTree(res.data.Table)
      this.treeData = treeData

      // debugger
      this.tableData = res.data.Table.filter(v => v.MenuCode === this.MenuCodeSave || v.ParentCode === this.MenuCodeSave)

      // if (this.clickData) {
      //   this.handleNodeClick(this.clickData)
      // } else {
      //   this.tableData = res.data.Table;
      // }

      // let Configuration = await MenuUpdate({
      //   MenuCode: data.MenuCode,
      //   IsPostBack: false,
      // })
      // this.saveConfigurationDate = result.data.Table[0]

      // debugger

    },

    handleOpen() {
      this.dialogFormVisible = true;
    },

    async FunrRowsAdd(Rows, ParmType) {
      //添加人员


    },

    close() {
      this.dialogMenuButton = false;
      this.dialogFormVisible = false;
      // alert(JSON.stringify(this.saveConfigurationDate))
    },
    onSubmit() {

    },
    //搜索重置
    refresh() {
      // alert(JSON.stringify(this.Search))
      this.getDataList();
    },
    reform() {
      this.Search = {
        // 查询条件
        // total: 0, // 总记录数
        pageSize: 13, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "009", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件

      };
      this.getDataList();
    },
    //读取列配置
    async getTableCols() {
      this.tableCols = []
      const res = await GetTableColsData({ InterID: "211" });
      this.tableCols = res.data;
      // debugger
      const MenuButtonres = await GetTableColsData({ InterID: "213" });
      this.MenuButtonCols = MenuButtonres.data;
      // console.log(this.tableCols); "MenuCode"

    },

    toTree(data, ParentCode = '') {
      let temp = [];
      data.forEach(item => {
        if (item.ParentCode == ParentCode) {
          const children = this.toTree(data, item.MenuCode);
          if (children.length) {
            item.children = children;
          }
          temp.push(item);
        }
        item.label = item.MenuName
        //debugger
      });
      return temp;
    },

    arrayToTree(data) {
      // 步骤1：创建一个空对象来存储结果树  
      // let tree = [{ label: '全部', children: [] }];
      let tree = [{ label: '全部', children: [] }];
      let treeNode = [];

      for (let i = 0; i < data.length; i++) {
        data[i].label = '⚙' + data[i].MenuName
        data[i].children = []
        if (data[i].ParentCode) {
          treeNode.push(data[i])
        } else {
          tree.push(data[i])
        }
      }
      // let Tree = [{label:'广东顺德浩尔云网络科技有限公司', children:[]}]
      // Tree[0].children = tree
      for (let i = 0; i < treeNode.length; i++) {
        treeNode[i].label = '▣' + treeNode[i].MenuName
        tree.some(v => {
          if (v.MenuCode == treeNode[i].ParentCode) {
            v.children.push(treeNode[i])
          }
        })
      }
      // debugger
      return tree; // 返回转换后的树形结构  
    },

    async getDataList() {
      const res = await getDataList({ data: JSON.stringify(this.Search) });
      this.tableData = res.data.Table;
      this.AppCode = res.data.Table[0].AppCode;

      const resTree = await getDataList({ data: JSON.stringify(this.SearchAll) });
      // this.tableDataSave = resTree.data.Table;
      const treeData = this.arrayToTree(resTree.data.Table)
      this.treeData = treeData;

      // debugger
      this.Search.total = res.data.Table1[0].RecordCount;
      this.billID = "";
    },

    OpenFindForm() {
      //打开搜索框
      this.SearchDialog = true;
      //计算外边距
      console.log(this.$refs.searchDialog.offsetHeight);
      this.DialogBtnMargin = this.$refs.searchDialog.offsetHeight - 40;
    },
    handlexportData() {
      funDownload("334", JSON.stringify(this.Search));
    }, handleIsfunEdit() {
      this.IsfunEdit = true;
    }, handleIsfunfail() {
      this.Isfunfail = true;
    },
    async handeAdd() {
      // 新建


      this.dialogFormVisible = true;
      let Configuration = await MenuUpdate({
        MenuCode: -1,
        IsPostBack: false,
      })
      this.saveConfigurationDate = Configuration.data.Table[0];
      this.saveConfigurationDate.ParentCode = this.MenuCodeSave;
      this.saveConfigurationDate.AppCode = this.AppCode;
      // debugger
      this.StepSN = Configuration.StepSN;

      this.move()
    },


    async handleEdit(scope, name) {
      if (name == "按钮") {
        this.dialogMenuButton = true;
        this.bottonID = scope.row.MenuCode
        let Configuration = await MenuButtonUpdate({
          billID: scope.row.MenuCode,
          IsPostBack: false,
        })
        this.MenuButtonData = Configuration.data.Table;
      } else {
        this.dialogFormVisible = true;
        let Configuration = await MenuUpdate({
          MenuCode: scope.row.MenuCode,
          IsPostBack: false,
        })
        this.saveConfigurationDate = Configuration.data.Table[0];
        this.StepSN = Configuration.StepSN;
      }
    },

    delData({ $index, row }) {
      this.$confirm('删除操作, 是否继续?', '提示', {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }).then(async () => {
        // alert(row.ID)
        // alert($index)
        // alert(JSON.stringify(this.MenuButtonData))
        const result = await MenuButtonDelet({
          billID: row.ID,
          // types: 1,
          // IsPostBack: false,
        });
        this.MenuButtonData.splice($index, 1)
        this.$message({
          type: "success",
          message: result.msg,
        });
      })
        .catch((err) => {
          console.error(err);
        });
    },
    handrowclick(row) {


      this.billID = row.billID;

    },
    handleclose() {
      if (this.billID != "") {
        this.$confirm('关单操作, 是否继续? 订单号：' + this.billID, '提示', {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        })
          .then(async () => {
            const result = await CloseForm({
              billID: this.billID,
              types: 1,
              IsPostBack: false,
            });
            this.getDataList();
            this.$message({
              type: "success",
              message: result.msg,
            });
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        this.$notify({
          title: "关单操作，请选择数据" + this.billID,
          dangerouslyUseHTMLString: true,
          message: "",
          type: "error",
        });
      }
    },


  }
}
</script>

<style lang="scss" scoped>
.modal-header {
  cursor: move;
  // margin-bottom: 10px;
}

.tree {
  // flex: 1;
  // width: 0;
  padding-left: 18px;
  height: 82vh;
  // border: 1px solid rgb(151, 180, 179);
  box-shadow: 0px 0px 2px #888;
  overflow: auto;

  /deep/ .el-tree-node__label {
    // text-shadow: -1px 1px 1px #888;  

    font-size: 15px;
  }

  /deep/ .el-tree-node__content:hover {
    background: rgba(49, 99, 173, 0.1);
  }

  /deep/ .is-current>.el-tree-node__content {
    background-color: rgba(49, 99, 173, 0.303);
    ;
  }
}

.app-container {
  .EditObjs-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 5px;
  }
}

.searchDialog ::v-deep .el-dialog__header {
  background: #409eff;
}

.searchDialog ::v-deep .el-dialog__title {
  color: #fff;
}

.searchDialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
</style>